package com.example.niu.qqapp


import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.view.animation.AnimationSet
import com.example.niu.qqapp.databinding.FragmentLoginBinding


// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 *
 */
class LoginFragment : Fragment() {

    private var _binding: FragmentLoginBinding? = null
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        _binding = FragmentLoginBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.textViewHistory.setOnClickListener {
            binding.layoutContext.visibility = View.INVISIBLE
            binding.layoutHistory.visibility = View.VISIBLE
            //创建3条历史记录菜单项，添加到layoutHistory中
            for (i in 0..2) {
                val layoutItem = activity!!.layoutInflater.inflate(
                    R.layout.login_history_item, null)
                //响应菜单项的点击，把它里面的信息填到输入框中。
                layoutItem.setOnClickListener {
                    binding.editTextQQNum.setText("123384328943894893")
                    binding.layoutContext.visibility = View.VISIBLE
                    binding.layoutHistory.visibility = View.INVISIBLE
                }
                binding.layoutHistory.addView(layoutItem)
            }

            //使用动画显示历史记录
            val set= AnimationUtils.loadAnimation(context,
                R.anim.login_history_anim) as AnimationSet
            binding.layoutHistory.startAnimation(set)
        }

        //响应最外层View的点击事件，隐藏历史菜单
        view.setOnClickListener {
            if(binding.layoutHistory.visibility == View.VISIBLE){
                binding.layoutContext.visibility = View.VISIBLE;
                binding.layoutHistory.visibility = View.INVISIBLE;
            }
        }

        //响应登录按钮的点击事件
        binding.buttonLogin.setOnClickListener {
            val fragmentManager = activity!!.supportFragmentManager
            val fragmentTransaction = fragmentManager.beginTransaction()
            val fragment = MainFragment()
            //替换掉FrameLayout中现有的Fragment
            fragmentTransaction.replace(R.id.fragment_container, fragment)
            //将这次切换放入后退栈中，这样可以在点后退键时自动返回上一个页面
            fragmentTransaction.addToBackStack("login")
            fragmentTransaction.commit()
        }
    }
}
